package org.spider.spiderweb.controller;

import org.apache.commons.lang3.StringUtils;
import org.spider.api.domain.utilDomain.Result;
import org.spider.api.utils.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/log")
public class LogController {
    @Value("${spider.workplace}")
    private String workspace;

    //根据任务id或者flow id
    @GetMapping
    public Result getLog(@RequestParam(name = "flowId", defaultValue = "") String flowId,
                         @RequestParam(name = "taskId", defaultValue = "0") Integer taskId) {
        if (StringUtils.isNoneBlank(flowId)) {
            try {
                File file = FileUtils.getLogFile(workspace,flowId,taskId);
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line = null;
                List<String> logs = new ArrayList<>();
                while ((line = br.readLine()) != null) {
                    logs.add(line);
                }
                br.close();
                return Result.getInstance(1, "success", logs);
            } catch (Exception e) {
                return Result.getInstance(1, "文件找不到");
            }
        } else {
            return Result.getInstance(1, "flowId为空");
        }
    }

    @GetMapping("/download")
    public void downloadLog(@RequestParam("flowId") String flow_id,
                              @RequestParam("taskId") Integer task_id,
                              HttpServletResponse response) throws IOException {
        File file = FileUtils.getLogFile(workspace,flow_id,task_id);
        InputStream in=null;
        ServletOutputStream outputStream=null;
        try {
            in = new FileInputStream(file);
            response.addHeader("Content-Disposition", "attachment");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setCharacterEncoding("UTF-8");
            outputStream = response.getOutputStream();
            FileCopyUtils.copy(in, outputStream);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if(in!=null) in.close();
            if(outputStream!=null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }
}

//filename= + URLEncoder.encode(fileName, StandardCharsets.UTF_8)